
package net.biaji.android.alephclient;

import java.util.ArrayList;

import net.biaji.alephclient.Book;
import net.biaji.alephclient.LibAgent;
import net.biaji.alephclient.NotLoginException;
import net.biaji.android.alephclient.data.DataFusionManager;
import net.biaji.android.alephclient.views.BookAdapter;
import android.app.Activity;
import android.os.AsyncTask;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.View;
import android.widget.ListView;

public class MainInfoFragment extends ListFragment {

    private BookDetailShower shower;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        shower = (BookDetailShower) activity;
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        if (shower != null) {
            shower.onBookSelected(((Book) getListAdapter().getItem(position)).getSN());
        }
    }

    public void load() {
        new AsyncTask<Void, Void, ArrayList<Book>>() {

            @Override
            protected ArrayList<Book> doInBackground(Void... params) {
                LibAgent agent = AgentSingleton.getInstance();

                try {
                    return agent.getBookInPocket();
                } catch (NotLoginException e) {
                    return null;
                }

            }

            @Override
            protected void onPreExecute() {

                if (getView() == null)
                    return;
                ArrayList<Book> booksInPocket = DataFusionManager.getInstance(getActivity())
                        .getBookInPocket();
                if (booksInPocket.size() > 0) {
                    setListAdapter(new BookAdapter(getActivity(), booksInPocket));
                    //setListShown(true);
                } else
                    setListShown(false);
            }

            @Override
            protected void onPostExecute(ArrayList<Book> result) {
                if (result != null) {
                    setListAdapter(new BookAdapter(getActivity(), result));
                    setListShown(true);
                    DataFusionManager.getInstance(getActivity()).updateBorrowInfo(result);
                } else
                    ;
                Log.d(getClass().toString(), "loadover");

            }

        }.execute();

    }

}
